#include "mqtt_dev.h"
extern "C"{
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
}

QString uname_get_dname(const char *userName)
{
    QString str = QString::fromLatin1(userName);
    int index = str.indexOf('&');
    return str.left(index);
}

QByteArray DATA_DEV_CLIENT_ID("pcf8591|securemode=3,signmethod=hmacsha1|");   //客户端ID
QByteArray DATA_DEV_USERNAME("pcf8591&a1fhO3qSWHg");    //用户名
QByteArray DATA_DEV_PASSWORD("db8e63059f63a017f5a497d04bea78866d2ecf02");

mqtt_dev::mqtt_dev(QObject *parent) : QObject(parent)
{

}

mqtt_dev::mqtt_dev(const char *serverURL, const char *clientid, int pers_type, void *pers_context)
{
    int rc = -1;
    auto pa = &this->client;
    if(MQTTCLIENT_SUCCESS != (rc = MQTTClient_create(pa,serverURL,clientid,pers_type,pers_context)))
    {
        printf("Failed to create client, return code %d\n", rc);
    }
}

mqtt_dev::~mqtt_dev()
{
    //断开与云平台的连接
    MQTTClient_disconnect(this->client,30);
    MQTTClient_destroy(&this->client);
}

/**
  @description:连接服务器端
  @param - options:客户端信息结构体
  @return: 操作结果
*/
int mqtt_dev::connect(MQTTClient_connectOptions *options)
{
    int rc = -1;

    if(MQTTCLIENT_SUCCESS != (rc = MQTTClient_connect(this->client,options)))
    {
        printf("Failed to connect, return code %d\n",rc);
        return EXIT_FAILURE;
    }
    return rc;
}

void mqtt_dev::disconnect()
{
    //断开与云平台的连接
    MQTTClient_disconnect(this->client,30);
}

/**
  @description:设置回调函数
  @param - context:传递给回调函数的参数
  @param - cl:断开连接回调函数
  @param - ma:接收到信息回调函数
  @param - dc:发布消息传递函数
  @return: 操作结果
*/
int mqtt_dev::setCallback(void *context, MQTTClient_connectionLost *cl,
                          MQTTClient_messageArrived *ma,
                          MQTTClient_deliveryComplete *dc)
{
    int rc = 0;

    if (MQTTCLIENT_SUCCESS !=
            (rc = MQTTClient_setCallbacks(this->client, context, cl,
            ma, dc)))
    {
        printf("Failed to set callbacks, return code %d\n", rc);
        rc = EXIT_FAILURE;
    }

    return rc;
}

/**
  @description:获取mqtt_dev对象中的MQTT客户端对象
  @return:MQTT客户端对象指针
*/
MQTTClient* mqtt_dev::get_client()
{
    return &this->client;
}

/**
  @description:从传入的用户名中获取到设备名
  @param - userName:用户名
  @return:设备名
*/
const char *mqtt_dev::get_dev_name(const char *userName)
{
    QString str = QString::fromLatin1(userName);
    int index = str.indexOf('&');
    return str.left(index).toUtf8().data();
}
